package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.AppAssist;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.UserResult;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.util.ActivitiesStackUtil;
import com.xfcycle.zebrabikegp.util.EncryptStringUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class LoginActivity extends RootActivity {

    private static final String TAG = "LoginActivity";

    private EditText et_login_username;
    private EditText et_login_password;

    private ImageView iv_login_icon;

    private TextView tv_forget_password_click;
    private TextView tv_regist;
    private TextView tv_server_address_sign;
    private RelativeLayout rl_cover;

    private Bundle bundle;
    private String log_username;
    private String log_password;

    private HandleDataBySharePreferencesUtil handleDateBySharePreferencesUtil;

    //服务器地址选择辅助参数，默认美服
    private Integer serverAddressTag = 0;
    //切换服务器地址辅助参数 按下时间
    private long downTime = 0;

    //选择服务弹出框
    private AlertDialog changeServerDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bundle = this.getIntent().getExtras();

        initView();
        initViewListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initViewContent();
    }

    /**
     * 初始化组件
     */
    public void initView() {
        et_login_username = (EditText) findViewById(R.id.et_login_username);
        et_login_password = (EditText) findViewById(R.id.et_login_password);

        iv_login_icon = (ImageView) findViewById(R.id.iv_login_icon);

        tv_forget_password_click = (TextView) findViewById(R.id.tv_forget_password_click);
        tv_regist = (TextView) findViewById(R.id.tv_regist);
        tv_server_address_sign = (TextView) findViewById(R.id.tv_server_address_sign);

        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);

        handleDateBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);

        //初始化极光推送
        JPushInterface.init(getApplicationContext());

        //初始化修改服务器提示框
        initChangeServerDialog();
    }

    /**
     * 添加组件监听事件
     */
    public void initViewListener() {

        //登录按钮监听事件
        iv_login_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断输入框是否为空
                if (null == et_login_username.getText() || null == et_login_password.getText() || "".equals(et_login_username.getText().toString()) || "".equals(et_login_password.getText().toString())) {
                    Toast.makeText(LoginActivity.this.getApplicationContext(), ToastConstant.HAS_EMPTY_INPUT_BOX, Toast.LENGTH_SHORT).show();
                    return;
                }
                //获得输入框的值
                log_username = et_login_username.getText().toString();
                log_password = et_login_password.getText().toString();
                //连接网络请求登录
                Map<String, String> params_log = new HashMap<>();
                params_log.put(WebConstant.LOGIN_PATH_EMAIL, log_username);
                params_log.put(WebConstant.LOGIN_PATH_PASSWORD, EncryptStringUtil.getMd5(log_password));
                new GetJsonFromWebJob(WebConstant.LOGIN_PATH, WebConstant.GET, params_log, REQUEST_SIGN_LOGIN, LoginActivity.this).start();

                //展示等待框
                if(null != rl_cover){
                    rl_cover.setVisibility(View.VISIBLE);
                }
            }
        });

        //忘记密码页面跳转
        tv_forget_password_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityChange(FIND_PASSWORD_ADDRESS_ACTIVITY, null, null);
            }
        });

        //注册页面跳转
        tv_regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityChange(REGIST_ADDRESS_ACTIVITY, null, null);
            }
        });

        //改变服务器地址 默认美服
        tv_server_address_sign.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        downTime = Calendar.getInstance().getTimeInMillis();
                        break;
                    case MotionEvent.ACTION_UP:
                        if((Calendar.getInstance().getTimeInMillis() - downTime) >= (5 * 1000)){
                            showDialog();
                        }
                        break;
                }

                return true;
            }
        });
    }

    /**
     * 初始化组件内容
     */
    public void initViewContent() {
        //取出记录中服务器选择的地址 并更新到界面中
        String strServerAddress = handleDateBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, SpConstant.SERVER_ADDRESS_TAG_KEY);
        if (null != strServerAddress && !"".equals(strServerAddress)) {
            Pattern pattern = Pattern.compile("[0-9]*");
            Matcher isNum = pattern.matcher(strServerAddress);
            if (isNum.matches()) {
                serverAddressTag = Integer.parseInt(strServerAddress);
            }
        } else {
            serverAddressTag = 0;
        }
        changeServerAddress();

        //首先将其全部置为空，随后在判断是否需要填充内容
        et_login_username.setText("");
        et_login_password.setText("");

        //将注册页面，修改密码获得的参数赋给组件
        if (null != bundle && null != bundle.getString("email_address") && null != bundle.getString("password")) {
            et_login_username.setText(bundle.getString("email_address"));
            et_login_password.setText(bundle.getString("password"));
            return;
        }

        //如果不是第一次登陆，从sp中取值，赋值给组件
        String sp_email = handleDateBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, "email");
        String sp_password = handleDateBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, "password");
        if (null != sp_email && null != sp_password) {
            et_login_username.setText(sp_email);
            et_login_password.setText(sp_password);
        }
    }

    /**
     * 处理从网络获取的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        //判断缺少参数
        if (webResult.contains("MissingParameter")) {
            rl_cover.setVisibility(View.GONE);
            Toast.makeText(this.getApplicationContext(), ToastConstant.NETWORK_FAILURE, Toast.LENGTH_SHORT).show();
            return;
        }

        //判断邮箱和密码不匹配
        if (webResult.contains("mismatch")) {
            rl_cover.setVisibility(View.GONE);
            Toast.makeText(this.getApplicationContext(), ToastConstant.EMAIL_AND_PASSWORD_WRONG, Toast.LENGTH_SHORT).show();
            return;
        }

        //判断账号不存在
        if (webResult.contains("none user")) {
            rl_cover.setVisibility(View.GONE);
            Toast.makeText(this.getApplicationContext(), ToastConstant.ACCOUNT_NOT_EXIST, Toast.LENGTH_SHORT).show();
            return;
        }

        //验证码验证成功，进行页面跳转
        if (REQUEST_SIGN_LOGIN == webSign && webResult.contains("api_token")) {
            //保存数据到SharePreferences中
            UserResult userResult = gson.fromJson(webResult, UserResult.class);

            //保存Api_Token
            AppAssist.ApiToken = userResult.getApi_token();

            //将数据存储到SharePreferences中
            Map<String, String> params_login_info = new HashMap<>();
            params_login_info.put("email", log_username);
            params_login_info.put("password", log_password);
            params_login_info.put("uid", userResult.getId());
            handleDateBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, params_login_info);

            //以用户Uid为别名 将其设置到JPush的服务器中
            setUserJpushAlias(userResult.getId());

            //页面跳转
            Map<String, String> params_change_activity_map = new HashMap<>();
            params_change_activity_map.put("uid", userResult.getId());
            activityChange(HOME_MAP_ACTIVITY, params_change_activity_map, null);

            return;
        }

        if(webResult.contains("defeat")){
            rl_cover.setVisibility(View.GONE);
            return;
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }

            return;
        }
    }

    /**
     * 监听回退按钮事件
     */
    @Override
    public void onBackPressed() {
        ActivitiesStackUtil.getInstance().exit();
    }

    /**
     * 变更服务器地址
     */
    private void changeServerAddress() {

        switch (serverAddressTag % 2) {
            //当前状态为美服
            case 0:
                tv_server_address_sign.setText("US");
                tv_server_address_sign.setTextColor(Color.TRANSPARENT);
                WebConstant.isCN = false;
                break;
            //当前状态为国服
            case 1:
                tv_server_address_sign.setText("CN");
                tv_server_address_sign.setTextColor(Color.WHITE);
                WebConstant.isCN = true;
                break;
        }

        //记录选择的服务器地址状态存储到sp手机中
        Map<String, String> serverAddressMap = new HashMap<>();
        serverAddressMap.put(SpConstant.SERVER_ADDRESS_TAG_KEY, (serverAddressTag % 2) + "");
        handleDateBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, serverAddressMap);
    }

    /***********************************************************************************************/
    /**                                  初始化修改服务器弹出框                                     **/
    /***********************************************************************************************/
    /**
     * 初始化更改服务器消息弹窗
     */
    private void initChangeServerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Notice");
        builder.setMessage("Change to " + (WebConstant.isCN ? "US" : "CN") + " mode.");

        //取消修改服务器
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismissDialog();
            }
        });

        //进入修改服务器流程
        builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                serverAddressTag++;
                changeServerAddress();
            }
        });

        //创建弹出框
        changeServerDialog = builder.create();
    }

    //隐藏弹出框
    private void dismissDialog() {
        if (null != changeServerDialog) {
            changeServerDialog.dismiss();
        }
    }

    //展示弹出框
    private void showDialog() {
        if (null != changeServerDialog && !changeServerDialog.isShowing()) {
            changeServerDialog.show();
        }
    }

    /***********************************************************************************************/
    /**                                   JPush设置别名                                            **/
    /***********************************************************************************************/
    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setUserJpushAlias(String alias) {

        if (TextUtils.isEmpty(alias)) {
            Log.e(TAG, "setUserJpushAlias: JPush 别名为空");
            return;
        }
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    /**
     * 配置设置别名后的回调函数
     */
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }
    };

}
